package com.atguigu.eduorder.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.eduorder.entity.Order;
import com.atguigu.eduorder.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author ycw
 * @since 2020-09-13
 */
@RestController
@RequestMapping("/eduorder/order")
@CrossOrigin
public class OrderController {
    @Autowired
    private OrderService orderService;
    //1.生成订单的方法  /购买课程，根据课程id生成订单
    @PostMapping("createOrder/{courseId}")
    //通过header【‘token’】这个值可以i得到，用request取到
    //通过里面的header把这个值取到
    public R saveOrder(@PathVariable String courseId, HttpServletRequest request) {
        //String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(request);
        //创建订单，返回订单号，后面根据订单号做支付
        String orderNo =
                orderService.createOrders(courseId,JwtUtils.getMemberIdByJwtToken(request));
        return R.ok().data("orderId",orderNo);
    }
    //2.根据订单id查询订单信息
    @GetMapping("getOrderInfo/{orderId}")
    public R getOrderInfo(@PathVariable String orderId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        Order order = orderService.getOne(wrapper);//一查询返回order对象
        return R.ok().data("item",order);
    }
    //根据课程id和用户id查询订单中订单状态
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    //为了后面返回方便，返回一个类型，不返回对象
    public Boolean isBuyCourse(@PathVariable String courseId,@PathVariable String memberId){
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",memberId);
        wrapper.eq("status",1);//支付状态，1代表 已经支付
        int count = orderService.count(wrapper);//count()表示上面条件中能不能查出记录，查出来，true反之false，gentone查详细记录， count查状态
        if (count> 0 ){//已支付
            return true;
        }else{
        return false;
        }
    }
}

